package com.classnet;

import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author karltinawi
 * @version 1.0
 */
public class CnetSession {
    
    private Date sessionStart;
    private EntityManager entityManager;
    
    public CnetSession(EntityManager entityManager) {
        if(entityManager == null)
            throw new NullPointerException("Expected EntityManager");
        
        sessionStart = new Date();
        this.entityManager = entityManager;
        beginTransaction();
    }
    
    private void beginTransaction() {
        entityManager.getTransaction().begin();
    }
    
    public void save() {
        entityManager.getTransaction().commit();
        beginTransaction();
    }
    
    public void rollback() {
        entityManager.getTransaction().rollback();
        beginTransaction();
    }
    
    public void close(boolean save) {
        if(save) entityManager.getTransaction().commit();
        else entityManager.getTransaction().rollback();
        entityManager.close();
    }
    
    public void persist(Object o) {
        entityManager.persist(o);
        save();
    }
    
    public void remove(Object o) {
        entityManager.remove(o);
        save();
    }
    
    public void refresh(Object o) {
        entityManager.refresh(o);
    }
    
    public Object find(Class cl, Object o) {
        return entityManager.find(cl, o);
    }
    
    public boolean contains(Object o) {
        return entityManager.contains(o);
    }
    
    public Query createNamedQuery(String q) {
        return entityManager.createNamedQuery(q);
    }
    
    public Query createQuery(String q) {
        return entityManager.createQuery(q);
    }
    
    public boolean isSOpen() {
        return entityManager.isOpen();
    }
    
    public final Date getSessionStart() {
        return sessionStart;
    }
    
    public final EntityManager getEntityManager() {
        return entityManager;
    }
}